type MsgType = string | Record<string, any> | Record<string, any>[];

export interface PaginationInfo {
    currentPage: number;
    totalRecords: number;
}

export default class ResponseResult<T> {
    returnResult?: T;
    resultList: T[] = [];
    page: number = 1;
    all: number = 0;
    operationResult: boolean = false;
    msg: MsgType = '';
    hasError: boolean = false;
    date: Date = new Date();
    errorNum: number | null = null;
    map: Record<string, any> = {};

    constructor(init?: Partial<ResponseResult<T>>) {
        Object.assign(this, init);
    }

    /** 分页信息 */
    get pagination(): PaginationInfo {
        return {
            currentPage: this.page,
            totalRecords: this.all
        };
    }

    /** 获取返回值列表，优先 returnResult，其次 resultList */
    get returnResults(): T[] {
        const results: T[] = [];

        if (
            this.returnResult !== null &&
            this.returnResult !== undefined &&
            this.returnResult !== '' &&
            this.returnResult !== 'null'
        ) {
            results.push(this.returnResult);
        }

        if (Array.isArray(this.resultList)) {
            results.push(...this.resultList);
        }

        return results;
    }

    /** 从 API 原始数据构建响应对象 */
    static fromApiResponse<T>(data: any): ResponseResult<T> {
        const result = new ResponseResult<T>();

        result.returnResult = data.return_result ?? data.returnResult;
        result.resultList = Array.isArray(data.resultList) ? data.resultList : [];
        result.page = typeof data.page === 'number' ? data.page : 1;
        result.all = typeof data.all === 'number' ? data.all : 0;
        result.operationResult = !!data.operationResult;
        result.hasError = !!data.hasError;
        result.errorNum = data.errorNum ?? null;
        result.map = typeof data.map === 'object' && data.map !== null ? data.map : {};
        result.msg = typeof data.msg === 'string' ? data.msg : null;
        const dateStr = data.retrunDate || data.retrunDate || data.date;
        result.date = dateStr ? new Date(dateStr) : new Date();
        return result;
    }

    /** 操作是否成功 */
    isSuccess(): boolean {
        return this.operationResult && !this.hasError;
    }

    /** 判断是否空响应或未返回有效信息 */
    isNull(): boolean {
        return (
            (!this.operationResult && !this.hasError) ||
            this.msg === null ||
            this.msg === undefined ||
            this.msg === ''
        );
    }

    /** 获取总页数 */
    getTotalPages(pageSize: number): number {
        return pageSize > 0 ? Math.ceil(this.all / pageSize) : 1;
    }
}
